package cn.hl.hm.filter;

import cn.hl.hm.util.token.TokenBean;
import cn.hl.hm.util.token.TokenUtil;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xianghan 2016年8月10日 下午5:43:13
 *
*/
public class TokenFilter extends OncePerRequestFilter{
	private Boolean isNeedCheck;
	private String actions;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		try {
			if(isNeedCheck ==null || actions==null){
				toMessage(response,500,"TokenFilter参数配置错误");
				return;
			}
			String action=request.getRequestURI();
			Boolean isCheck = isCheck(action,actions,isNeedCheck);
			if(isCheck){
				Cookie cookie=null;
				Cookie[] cookies = request.getCookies();
				if (cookies!=null) {
					for (Cookie c : cookies) {
						if (c.getName().endsWith("Token")) {
							cookie=c;
							continue;
						}
					}
				}
				if(cookie==null){
					toMessage(response,9999,"Token为空，校验失败");
					return ;
				}else{
					TokenBean tokenBean = TokenUtil.getTokenBean(cookie.getValue());
					if (tokenBean==null || tokenBean.getId()==null) {
						toMessage(response,9999,"Token不存在，校验失败");
						return ;
					}
				}
			}
		} catch (Exception ie) {
			ie.printStackTrace();
			toMessage(response,500,"发生异常，Token校验失败");
			return;
		}
		doFilter(request, response, filterChain, request);
	}

	public static void main(String[] args) {
		Boolean isCheck=false;
		String action="/v2/user/user.logout";
		String actions="/v2/common/*;/v2/user/user.get;/v2/user/user.login;/v2/user/user.logout";
		System.out.println("是否校验："+isCheck(action,actions,isCheck));

		int code=0;
		String message="成功";
		System.out.println("{\"data\":\"\",\"state\":{\"stateMessage\":\""+message+"\",\"stateCode\":"+code+"}}");
	}
	
	private static boolean isCheck(String action,String actions,boolean isCheck){
		String[] actionList=actions.split(";");
		boolean isInList=isInList(action, actionList);
		if(isCheck){//需要校验的
			//不在列表中不校验
			if(!isInList){
				isCheck=false;
			}
		}else{//不需要校验的
			//不在列表中需要校验
			if(!isInList){
				isCheck=true;
			}
		}
		return isCheck;
	}

	/**
	 *
	 * @author xianghan
	 * @param action
	 * @param actionList
	 * @return
	 */
	private static Boolean isInList(String action, String[] actionList) {
		boolean isInList=false;
		try {
			for(String a:actionList){
				if(a.indexOf("*")!=-1){
					String path=a.replace("*", "");
					if(action.indexOf(path)!=-1){
						isInList=true;
						break;
					}
				}else{
					if(action.equals(a)){
						isInList=true;
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return isInList;
	}

	/**
	 *
	 * @author xianghan
	 * @param request
	 * @param response
	 * @param filterChain
	 * @param requestWrapper
	 * @throws IOException
	 * @throws ServletException
	 */
	public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain,
			ServletRequest requestWrapper) throws IOException, ServletException {
		response.setCharacterEncoding("UTF-8");
		if (null == requestWrapper) {
			filterChain.doFilter(request, response);
		} else {
			filterChain.doFilter(requestWrapper, response);
		}
	}

	/**
	 *
	 * @author xianghan
	 * @param response
	 * @throws IOException
	 */
	public void toMessage(HttpServletResponse response,int code, String message) throws IOException {
		response.setHeader("Content-type", "application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().println("{\"data\":null,\"state\":{\"stateMessage\":\""+message+"\",\"stateCode\":"+code+"}}");
	}

	public void setIsNeedCheck(Boolean isNeedCheck) {
		this.isNeedCheck = isNeedCheck;
	}

	public void setActions(String actions) {
		this.actions = actions;
	}
}
